import React,{ useState,useEffect,useRef } from 'react'
import { Card,Button, message,Modal,Input,Cascader } from 'antd';
import { PlusOutlined,DoubleRightOutlined,LoadingOutlined } from '@ant-design/icons';
import { connect } from 'react-redux';
import MyTable from './components/Table'

import { reqCategories,reqCategoryRename,reqAddCategory } from '../../api/index'
import { setCategories } from '../../redux/actions';
import './Category.css'

/* 
  商品分类路由
*/
export default connect(()=>({}),{setCategories})(function Category(props) {

  const {setCategories}=props

  const [title,setTitle]=useState((<Button type='link' style={{color:'#000'}} disabled>一级分类列表</Button>))
  const [list,setList]=useState([])
  const [options,setOptions]=useState([])
  const [data,setData]=useState([])
  const [actionInfo,setActionInfo]=useState([])
  const [loading,setLoading]=useState(false)
  const [isModalVisible,setIsModalVisible]=useState(false)
  const [submit,setSubmit]=useState(null)
  const add_input = useRef()

  const toAddCategory=()=>{
    if(!add_input.current.state.value.trim()){
      message.warn('分类名不能为空')
      return false
    }
    submit.name=add_input.current.state.value
    reqAddCategory(submit).then(res=>{
      message.success(res.message)
      setList([])
      setIsModalVisible(false)
    })
    setSubmit(null)
    setList([])
    add_input.current.state.value=''    
  }

  function setDataContent(newData){
    if(Array.isArray(newData)){
      setData(newData)
      setActionInfo([])
      titleChange([])
    }else{
      setData(list[actionInfo[newData].index].category)
      setActionInfo(actionInfo.slice(0,newData+1))
      titleChange(actionInfo)
    }
  }

  const titleChange=(actions)=>{
    if(actions.length===0){
      setTitle((<Button type='link' style={{color:'#000'}} disabled>一级分类列表</Button>))
      return
    }
    setTitle(
      actions.length+1===1?(<Button key='level_1' type='link' style={{color:'#000'}} disabled>一级分类列表</Button>):(
        <>
          <Button key='btn_title' type='link' onClick={()=>setDataContent(list)}>一级分类列表</Button>
          {
            actions.map((i,index)=>{
              return (<span key={i.id}>
                <DoubleRightOutlined/>
                <Button style={actions.length-1===index?{color:'#000'}:{}} type='link' disabled={actions.length-1===index} onClick={actions.length-1===index?null:()=>setDataContent(index)}>{i.name}</Button>
              </span>)
            })
          }
        </>
      )
    )
    setData(new Array(actions.length).fill(0).reduce((pre,cur,index)=>pre[actions[index].index].children,list))
  }

  const changeCategory=(submit)=>{
    console.log(submit)
    reqCategoryRename(submit).then(res=>{
      message.success(res.message)
      setList([])
    })
    setList([])
  }

  const onChange=(label,options)=>{
    let add_obj={}
    if(options.length===1&&options[0].id==='-1'){//选择添加一级分类
    }else if(options.length===2&&options[1].id==='-1'){//选择添加二级分类
      add_obj.id=options[0].id
    }else if(options.length===2&&options[1].id!=='-1'){//选择添加三级分类
      add_obj.id=options[0].id
      add_obj.parent_index=list.find(i=>i.id===options[0].id).children.findIndex(i=>i.id===options[1].id)
    }
    setSubmit(add_obj)
  }

  const displayRender=(label,options)=>{
    return label.slice(0,2).join(' >> ')
  }

  useEffect(() => {
    async function getData(){
      setLoading(true)
      let list= await reqCategories()
      setList(list.map(i=>{i.id=i._id;delete i._id;return i}))
      setCategories(list)
      setOptions((()=>{
        console.log(list)
        let arr=list.reduce((pre,cur)=>{
          let obj={id:cur.id,name:cur.name,children:[{name:'二级分类',id:'-1'},...cur.children.map(i=>({id:i.id,name:i.name}))]}
          pre.push(obj)
          return pre
        },[{name:'一级分类',id:'-1'}])
        return arr})())
      setLoading(false)
      setDataContent(list)
    }
    if(list.length===0){
      getData()
    }
    
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [list]);

  return (
    <div className='category'>
      <Card className='category-card' title={title} extra={<Button type="primary" onClick={()=>setIsModalVisible(true)}><PlusOutlined /> 添加</Button>} style={{ width:'100%',height:'100%' }}>
        <MyTable list={data} setActionInfo={setActionInfo} changeCategory={changeCategory} actionInfo={actionInfo} titleChange={titleChange} loading={loading}></MyTable>
      </Card>
      <Modal title="添加分类" visible={isModalVisible} onOk={toAddCategory} onCancel={()=>setIsModalVisible(false)}>
        <Cascader className='category-add_category-cascader' options={options} notFoundContent={<LoadingOutlined />} onChange={onChange} displayRender={displayRender} fieldNames={{ label:'name',value:'name',children:'children'}} placeholder='添加一级分类'/>
        <Input ref={add_input} placeholder='请输入分类名'></Input>
      </Modal>
    </div>
  )
})